package com.leetcode.sorts.linked;

/**
 * @Author: WuPeng
 * @Date: 2021/5/26 6:13 下午
 *
 * 019: 删除链表的倒数第n个节点
 *
 */
public class DeleteNode_019 {
    public static ListNode solution(ListNode head, int n){

        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;

        ListNode pre  = dummyHead;
        ListNode slow = head;
        ListNode fast = head;

        while (n-- > 0){
            fast = fast.next;
        }

        while(fast != null){
            slow = slow.next;
            pre = pre.next;
            fast = fast.next;
        }
        pre.next = slow.next;

        return dummyHead.next;
    }

    public static void main(String[] args) {
        ListNode head  = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(3);
        ListNode node5 = new ListNode(2);
        ListNode node6 = new ListNode(1);
        head.next  = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        ListNode node = solution(head, 2);

        while (node != null){
            System.out.printf("%s\t", node.val);
            node = node.next;
        }

    }

}
